package com.qsmx.qingqiuticket.app.delegate;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.al.printerlib.device.CallbackListener;
import com.al.printerlib.device.Printer;
import com.al.printerlib.device.PrinterStatus;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.log.AtmosLogger;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateOrderPayBinding;
import com.qsmx.qingqiuticket.app.delegate.mem.MemTicketListDelegate;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.CouponEntity;
import com.qsmx.qingqiuticket.app.entity.GrowInfoEntity;
import com.qsmx.qingqiuticket.app.entity.PayOrderEntity;
import com.qsmx.qingqiuticket.app.entity.PrintEntity;
import com.qsmx.qingqiuticket.app.entity.PrintInfoEntity;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.event.CouponCheckRefreshEvent;
import com.qsmx.qingqiuticket.app.event.LoginEvent;
import com.qsmx.qingqiuticket.app.event.PrintFinishEvent;
import com.qsmx.qingqiuticket.app.event.QrScanEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.DoubleUtils;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.LogUtils;
import com.qsmx.qingqiuticket.app.util.PrintUtil;
import com.qsmx.qingqiuticket.app.util.SaveHelper;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class OrderPayDelegate extends AtmosDelegate {
    private List<PrintEntity.BodyBean.TicketPrintInfosBean> mPrintData;
    private PrintEntity mPayData;
    private int mAllPrintTicketNum;
    private String payCode;
    private String packageId = "";
    private String sessionId = "";
    private String orderNo = "";
    private double packagePrice = 0;
    private int sessionNum = 0;
    private String sessionTime = "";
    private String sessionNo = "";
    private String giveIntegral = "";
    private String giveGrowth = "";
    private double totalPrice = 0;
    private double couponPrice = 0.0;
    private String selectCouponId;
    private DelegateOrderPayBinding mBinding = null;

    private Dialog errorRetryDialog;
    private int errorTimes = 0;

    private AppCompatTextView tvErrorBackNow;
    private CountDownTimerUtil errorBackTime;

    private CountDownTimerUtil timer;

    private CountDownTimerUtil backTimer;
    private String beforeOrderNo;

    /**
     * 打印中弹窗
     */
    private Dialog mPrintTicketDialog;
    private AppCompatTextView tvTicketOutNum;
    private AppCompatTextView tvPrintGetTicket;
    private AppCompatTextView tvPrintFinishTime;
    private AppCompatTextView tvPrintStatus;
    private AppCompatTextView tvBackNow;
    private AppCompatTextView tvPrintErrorInfo;
    private AppCompatTextView tvRetry;
    private Dialog printErrorDialog;

    private Dialog mustLoginDialog;
    private Dialog unMustLoginDialog;
    private Dialog couponTipsDialog;

    @Override
    public Object setLayout() {
        return R.layout.delegate_order_pay;
    }

    public static OrderPayDelegate create(String orderNo, String packageId, String sessionId, double packagePrice, int sessionNum, String sessionTime, String sessionNo, String giveIntegral, String giveGrowth) {

        final Bundle args = new Bundle();
        args.putString(FusionTag.ORDER_NO, orderNo);
        args.putString(FusionTag.PACKAGE_ID, packageId);
        args.putString(FusionTag.SESSION_ID, sessionId);
        args.putDouble(FusionTag.PACKAGE_PRICE, packagePrice);
        args.putInt(FusionTag.SESSION_NUM, sessionNum);
        args.putString(FusionTag.SESSION_TIME, sessionTime);
        args.putString(FusionTag.SESSION_NO, sessionNo);
        args.putString(FusionTag.GIVE_INTEGRAL, giveIntegral);
        args.putString(FusionTag.GIVE_GROWTH, giveGrowth);

        final OrderPayDelegate delegate = new OrderPayDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            orderNo = args.getString(FusionTag.ORDER_NO);
            packageId = args.getString(FusionTag.ORDER_NO);
            packageId = args.getString(FusionTag.PACKAGE_ID);
            sessionId = args.getString(FusionTag.SESSION_ID);
            packagePrice = args.getDouble(FusionTag.PACKAGE_PRICE);
            sessionNum = args.getInt(FusionTag.SESSION_NUM);
            sessionTime = args.getString(FusionTag.SESSION_TIME);
            sessionNo = args.getString(FusionTag.SESSION_NO);
            giveIntegral = args.getString(FusionTag.GIVE_INTEGRAL);
            giveGrowth = args.getString(FusionTag.GIVE_GROWTH);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        totalPrice = DoubleUtils.formatDecimal(packagePrice * sessionNum - couponPrice);
        if (AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE).equals("1") || StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE))) {
            if (FusionData.mMemData == null) {
                showLoginMemDialog();
            } else {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        } else {
            if (FusionData.mMemData == null) {
                showUnMustLoginMemDialog();
            } else {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        }

        mBinding = DelegateOrderPayBinding.bind(rootView);
        if (FusionData.mMemData != null) {
            mBinding.tvMemStatus.setText(FusionData.mMemData.getPhone());
            mBinding.tvMemStatus.setVisibility(View.VISIBLE);
            mBinding.tvPoint.setText(giveIntegral);
            mBinding.tvUpPoint.setText(giveGrowth);
            getCouponList();
        } else {
            mBinding.tvMemStatus.setText("未登录");
            mBinding.tvPoint.setText("0");
            mBinding.tvUpPoint.setText("0");
        }

        mBinding.tvOrderPrice.setText("¥" + totalPrice);
        mBinding.tvPrice.setText("¥" + DoubleUtils.formatDecimal(packagePrice * sessionNum));
        mBinding.tvIntoTime.setText(sessionTime);
        mBinding.tvSessionNo.setText("场次" + sessionNo);
        if (StringUtil.isNotEmpty(sessionTime) && StringUtil.isNotEmpty(sessionNo)) {
            mBinding.tvIntoTimeTitle.setVisibility(View.GONE);
            mBinding.tvIntoTime.setVisibility(View.GONE);
            mBinding.tvSessionNoTitle.setVisibility(View.GONE);
            mBinding.tvSessionNo.setVisibility(View.GONE);
        } else {
            mBinding.tvIntoTimeTitle.setVisibility(View.VISIBLE);
            mBinding.tvIntoTime.setVisibility(View.VISIBLE);
            mBinding.tvSessionNoTitle.setVisibility(View.VISIBLE);
            mBinding.tvSessionNo.setVisibility(View.VISIBLE);
        }
        startCountDownBackTime(120);

        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    cleanSessionInfo();
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.tvMemStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (FusionData.mMemData == null) {
                        getSupportDelegate().start(new HomeLoginMemDelegate());
                    }
                }
            }
        });

        mBinding.ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (FusionData.mMemData == null) {
                        getSupportDelegate().start(new HomeLoginMemDelegate());
                    }
                }
            }
        });

        mBinding.clSelectCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (FusionData.mMemData != null) {
                        getSupportDelegate().start(CouponDelegate.create(String.valueOf(DoubleUtils.formatDecimal(packagePrice * sessionNum)), selectCouponId));
                    } else {
                        getSupportDelegate().start(new HomeLoginMemDelegate());
                    }
                }
            }
        });

        if (FusionData.mMemData != null) {
            getIntegerAndGrow();
        }
    }

    private void cleanSessionInfo() {

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));

        HttpHelper.RestClientPostRaw(params, HttpUrl.CLEAR_SESSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void showLoginMemDialog() {
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        mustLoginDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        mustLoginDialog.setCancelable(false);
        mustLoginDialog.show();
        Window window = mustLoginDialog.getWindow();
        window.setContentView(R.layout.dialog_login_mem_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvLogin = window.findViewById(R.id.tv_login);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mustLoginDialog.dismiss();
                getSupportDelegate().start(new HomeLoginMemDelegate());
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mustLoginDialog.dismiss();
                getSupportDelegate().pop();
            }
        });
    }

    private void showCouponTipsDialog() {
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        couponTipsDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        couponTipsDialog.setCancelable(true);
        couponTipsDialog.show();
        Window window = couponTipsDialog.getWindow();
        window.setContentView(R.layout.dialog_use_coupon_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvUseCoupon = window.findViewById(R.id.tv_use_coupon);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        tvUseCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                couponTipsDialog.dismiss();
                getSupportDelegate().start(CouponDelegate.create(String.valueOf(DoubleUtils.formatDecimal(packagePrice * sessionNum)), selectCouponId));
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                couponTipsDialog.dismiss();
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });

        couponTipsDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });
    }

    private void showUnMustLoginMemDialog() {
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        unMustLoginDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        unMustLoginDialog.setCancelable(true);
        unMustLoginDialog.show();
        Window window = unMustLoginDialog.getWindow();
        window.setContentView(R.layout.dialog_un_must_login_mem_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvLogin = window.findViewById(R.id.tv_login);
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unMustLoginDialog.dismiss();
                getSupportDelegate().start(new HomeLoginMemDelegate());
            }
        });

        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unMustLoginDialog.dismiss();
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });

        unMustLoginDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                FusionCode.QrIsLoading = false;
            }
        });
    }

    private void showPrintErrorDialog(String errorInfo) {
        printErrorDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        printErrorDialog.setCancelable(false);
        printErrorDialog.show();
        Window window = printErrorDialog.getWindow();
        window.setContentView(R.layout.dialog_print_error);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvErrorInfo = window.findViewById(R.id.tv_print_error_info);

        tvErrorInfo.setText(errorInfo);

        startErrorCountDownTime(10);

        tvErrorBackNow = window.findViewById(R.id.tv_back_now);

        tvErrorBackNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                printErrorDialog.dismiss();
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        });

        tvErrorBackNow.setClickable(false);
        tvErrorBackNow.setBackgroundResource(R.drawable.round_corner_dark_gray_bg_gray_line);
    }

    private void getCouponList() {
        JSONObject params = new JSONObject();
        params.put("storeId", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
        params.put("goodsPrice", String.valueOf(DoubleUtils.formatDecimal(packagePrice * sessionNum)));
        params.put("useRange", "1");
        params.put("memberUuid", FusionData.mMemData.getUserId());

        HttpHelper.RestClientPostRaw(params, HttpUrl.COUPON_LIST,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        try {
                            Type type = new TypeToken<CouponEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            CouponEntity mCouponEntity = gson.fromJson(response, type);
                            if (mCouponEntity.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mCouponEntity.getBody() != null && !mCouponEntity.getBody().isEmpty()) {
                                    showCouponTipsDialog();
                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                    }
                });

    }

    private void payOrder(String payCode) {
        CameraManager.takeVideo(getContext(), orderNo, getProxyActivity());
        if (backTimer != null) {
            backTimer.cancel();
        }
        mPrintData = new ArrayList<>();

        DialogUtil.showLoadingDialog(getContext(), "正在支付...");
        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        if (mPayData != null && mPayData.getBody() != null && StringUtil.isNotEmpty(mPayData.getBody().getOrderNo())) {
            params.put("beforeOrderNo", mPayData.getBody().getOrderNo());
            long orderNoTime = System.currentTimeMillis();
            orderNo = "SP" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);
        }
        params.put("newOrderNo", orderNo);
        params.put("packageId", packageId);
        if (FusionData.mMemData != null) {
            params.put("memberUuid", FusionData.mMemData.getUserId());
        }
        params.put("buyQuantity", sessionNum);
        params.put("payCode", payCode);
        if (totalPrice - couponPrice < 0) {
            params.put("totalPrice", DoubleUtils.formatDecimal(0));
        } else {
            params.put("totalPrice", DoubleUtils.formatDecimal(totalPrice - couponPrice));
        }
        params.put("couponRecordId", selectCouponId);
        LogUtils.saveLog2File(params.toString(), true);

        HttpHelper.RestClientPostRaw(params, HttpUrl.PAY_ORDER,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        LogUtils.saveLog2File(response, false);
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<PrintEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            mPayData = gson.fromJson(response, type);
                            if (mPayData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                for (PrintEntity.BodyBean.TicketPrintInfosBean data : mPayData.getBody().getTicketPrintInfos()) {
                                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_BRAND_NAME, data.getPrintBrandName());
                                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_STORE_NAME, data.getPrintStoreName());
                                    if (StringUtil.isNotEmpty(data.getPrintId())) {
                                        mPrintData.add(data);
                                    }
                                }
                                mAllPrintTicketNum = mPrintData.size();

                                if (!mPrintData.isEmpty()) {
                                    showPrintTicketDialog();
                                    startPrintTicket();
                                }
                            } else if (mPayData.getHeader().getCode().equals("10")) {
                                showPrintErrorDialog(mPayData.getHeader().getMessage());
                            } else if (mPayData.getHeader().getCode().equals("100009994")) {
                                showCardErrorRetryDialog(getContext(), payCode, mPayData.getHeader().getMessage());
//                                DialogUtil.showCardErrorDialog(OrderPayDelegate.this, getContext(), mPayData.getHeader().getMessage(), "确认", new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        DialogUtil.dismissErrorDialog();
//                                        startCountDownBackTime(120);
//                                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
//                                        FusionCode.QrIsLoading = false;
//                                    }
//                                });
                            } else if (mPayData.getHeader().getCode().equals("100009995")) {
                                DialogUtil.showCardErrorDialog(OrderPayDelegate.this, getContext(), mPayData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        DialogUtil.dismissErrorDialog();
                                        startCountDownBackTime(120);
                                        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                                        FusionCode.QrIsLoading = false;
                                    }
                                });
                            } else {
                                DialogUtil.showCardErrorDialog(OrderPayDelegate.this, getContext(), mPayData.getHeader().getMessage(), "确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.dismissErrorDialog();
                                        getSupportDelegate().pop();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            showCardErrorRetryDialog(getContext(), payCode, e.getMessage());
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        showCardErrorRetryDialog(getContext(), payCode, msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        showCardErrorRetryDialog(getContext(), payCode, "网络错误");
                    }
                });
    }

    private void startPrintTicket() {
        if (mPrintData != null && !mPrintData.isEmpty()) {
            PrintInfoEntity data = new PrintInfoEntity();
            data.setId(mPrintData.get(0).getTicketId());
            data.setOrderNo(mPrintData.get(0).getOrderNo());
            data.setType(mPrintData.get(0).getTradeType());
            data.setQrCode(mPrintData.get(0).getBindUuid());
            data.setSessionNo(mPrintData.get(0).getSessionNo());
            data.setSessionDate(mPrintData.get(0).getSessionDate());
            data.setSessionTime(mPrintData.get(0).getSessionStartTime() + "-" + mPrintData.get(0).getSessionEndTime());
            data.setPrintWord(mPrintData.get(0).getPrintedWord());
            data.setTicketPrintName(mPrintData.get(0).getTicketPrintName());

            PrintUtil.doPrint(requireContext(), mPrintData.get(0).getPrintId(), tvPrintErrorInfo, tvRetry, data, getProxyActivity());
        } else {
//            postDelayed(this::stopRecording, 10000); // 10 秒后停止录制
            // 停止录制视频
            new android.os.Handler().postDelayed(CameraManager::stopRecording, 10000); // 10 秒后停止录制
            FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            tvBackNow.setVisibility(View.VISIBLE);
            tvPrintStatus.setText("打印完成");
            tvPrintGetTicket.setVisibility(View.VISIBLE);
            tvPrintFinishTime.setVisibility(View.VISIBLE);
            startCountDownTime(5);
        }
        tvTicketOutNum.setText(Html.fromHtml(String.format(getString(R.string.print_ticket_num), String.valueOf(mAllPrintTicketNum - mPrintData.size()), String.valueOf(mAllPrintTicketNum))));
    }

    @SuppressLint("SetTextI18n")
    public void showPrintTicketDialog() {
        if (mPrintTicketDialog != null) {
            mPrintTicketDialog.dismiss();
        } else {
            mPrintTicketDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }
        SoundPlayUtils.play(4);

        mPrintTicketDialog.setCancelable(false);
        Window window = mPrintTicketDialog.getWindow();
        window.setContentView(R.layout.dialog_ticket_out);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        tvPrintStatus = window.findViewById(R.id.tv_print_status);
        tvTicketOutNum = window.findViewById(R.id.tv_ticket_out_num);
        tvPrintGetTicket = window.findViewById(R.id.tv_print_get_ticket);
        tvPrintFinishTime = window.findViewById(R.id.tv_print_finish_time);
        tvBackNow = window.findViewById(R.id.tv_back_now);
        tvPrintErrorInfo = window.findViewById(R.id.tv_print_error_info);
        tvRetry = window.findViewById(R.id.tv_retry);
        AppCompatTextView tvOrderNo = window.findViewById(R.id.tv_order_no);

        tvOrderNo.setText("订单号：" + orderNo);

        tvRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPrintTicket();
                tvRetry.setVisibility(View.GONE);
                tvPrintErrorInfo.setVisibility(View.GONE);
            }
        });

        tvBackNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPrintTicketDialog.dismiss();
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));
                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        });
        mPrintTicketDialog.show();
    }

    public void showCardErrorRetryDialog(final Context mContext, final String qrCode, String errInfo) {
        if (errorRetryDialog != null) {
            errorRetryDialog.dismiss();
        } else {
            errorRetryDialog = new Dialog(mContext, com.qsmx.core.R.style.dialog);
        }
        errorRetryDialog.setCancelable(false);
        Window window = errorRetryDialog.getWindow();
        window.setContentView(R.layout.dialog_sale_error_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvErrorInfo = window.findViewById(R.id.tv_error_info);
        AppCompatTextView tvRetry = window.findViewById(R.id.tv_retry);
        AppCompatTextView tvService = window.findViewById(R.id.tv_service);
        AppCompatTextView tvServiceLine = window.findViewById(R.id.tv_service_line);

        if (errorTimes >= 3) {
            tvService.setVisibility(View.VISIBLE);
            tvServiceLine.setVisibility(View.VISIBLE);
        } else {
            tvService.setVisibility(View.GONE);
            tvServiceLine.setVisibility(View.GONE);
        }
        tvErrorInfo.setText(errInfo);
        tvRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    errorTimes = errorTimes + 1;
                    errorRetryDialog.dismiss();
                    if (StringUtil.isNotEmpty(qrCode)) {
                        payOrder(qrCode);
                    }
                }
            }
        });

        tvService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    showServiceDialog(getContext());
                }
            }
        });

        errorRetryDialog.show();
    }

    public void showServiceDialog(final Context mContext) {
        final Dialog serviceDialog = new Dialog(mContext, com.qsmx.core.R.style.dialog);
        serviceDialog.setCancelable(false);
        Window window = serviceDialog.getWindow();
        window.setContentView(R.layout.dialog_service_pwd);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        final AppCompatEditText etPwd = window.findViewById(R.id.et_pwd);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);
        AppCompatImageView ivClose = window.findViewById(R.id.iv_close);

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceDialog.dismiss();
            }
        });

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (StringUtil.isNotEmpty(etPwd.getText().toString())) {
                        if (etPwd.getText().toString().equals(AtmosPreference.getCustomStringPre(FusionPre.BACK_PASSWORD))) {
                            //TODO 订单标记为已处理
                            if (errorRetryDialog != null && errorRetryDialog.isShowing()) {
                                errorRetryDialog.dismiss();
                            }
                            serviceDialog.dismiss();
                            showDoSureDialog(getContext());
                        } else {
                            DialogUtil.showCardErrorDialog(OrderPayDelegate.this, mContext, "请输入正确的管理员密码", "确定");
                        }
                    } else {
                        DialogUtil.showCardErrorDialog(OrderPayDelegate.this, mContext, "管理员密码不可为空", "确定");
                    }
                }
            }
        });
        etPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPwd.requestFocus();
                etPwd.setCursorVisible(true);
            }
        });
        serviceDialog.show();
    }

    @SuppressLint("SetTextI18n")
    public void showDoSureDialog(final Context mContext) {
        final Dialog doSureDialog = new Dialog(mContext, com.qsmx.core.R.style.dialog);
        doSureDialog.setCancelable(false);
        Window window = doSureDialog.getWindow();
        window.setContentView(R.layout.dialog_service_do_sure);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        int height = (int) (DimenUtil.getScreenHeight() * 0.9);

        window.setLayout(width, height);

        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);
        AppCompatTextView tvMachineNo = window.findViewById(R.id.tv_machine_no);
        AppCompatTextView tvPayMoney = window.findViewById(R.id.tv_pay_money);
        AppCompatTextView tvMemInfo = window.findViewById(R.id.tv_mem_info);
        AppCompatTextView tvOrderTime = window.findViewById(R.id.tv_order_time);
        AppCompatTextView tvOrderNo = window.findViewById(R.id.tv_order_no);
        AppCompatTextView tvDoFun = window.findViewById(R.id.tv_do_fun);
        AppCompatTextView tvRecord = window.findViewById(R.id.tv_record);

        tvRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraManager.showOpenImgDialog(requireContext(), CameraManager.getVideos(orderNo));
            }
        });

        tvMachineNo.setText(AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        tvPayMoney.setText("￥" + totalPrice);
        if (FusionData.mMemData != null) {
            tvMemInfo.setText(FusionData.mMemData.getPhone());
        } else {
            tvMemInfo.setText("");
        }
        tvOrderTime.setText(StringUtil.getDateByTimestamp(System.currentTimeMillis()));
        tvOrderNo.setText(orderNo);
        tvDoFun.setText("交易失败，给您带来不便，敬请见谅！");
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    doSureDialog.dismiss();
                    getSupportDelegate().popTo(HomeDelegate.class, false);
                }
            }
        });
        doSureDialog.show();
    }

    private void printFinish(String printId, String orderNo, String ticketId) {
        DialogUtil.showLoadingDialog(requireContext(), "正在记录门票信息...");
        long orderNoTime = System.currentTimeMillis();
        String serialNo = "LS" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

        JSONObject params = new JSONObject();
        params.put("serialNo", serialNo);
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("printId", printId);
        params.put("orderNo", orderNo);
        params.put("ticketId", ticketId);
        params.put("changeNum", "1");
        params.put("changeType", "1");
        if (printId.equals("1")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
        } else if (printId.equals("2")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
        } else if (printId.equals("3")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));
        }

        HttpHelper.RestClientPostRaw(params, HttpUrl.PRINT_RECORD,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        Type type = new TypeToken<BaseEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        BaseEntity mData = gson.fromJson(response, type);
                        if (mData.getHeader().getCode().equals("200")) {
                            if (printId.equals("1")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("2")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("3")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM), 0) - 1));
                            }
                            mPrintData.remove(0);
                            startPrintTicket();
                        } else {
                            DialogUtil.showCardErrorDialog(OrderPayDelegate.this, requireContext(), mData.getHeader().getMessage(), "重试", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    printFinish(printId, orderNo, ticketId);
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(OrderPayDelegate.this, requireContext(), msg, "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(OrderPayDelegate.this, requireContext(), getString(R.string.un_know_net_error), "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                });
    }

    private void startCountDownBackTime(final long time) {
        if (backTimer != null) {
            backTimer.cancel();
        }
        backTimer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvTime.setText(String.format(getString(R.string.back_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                if (mPrintTicketDialog != null) {
                    mPrintTicketDialog.dismiss();
                }
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        backTimer.start();// 开始计时
    }

    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvPrintFinishTime.setText(String.format(getString(R.string.finish_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                if (mPrintTicketDialog != null) {
                    mPrintTicketDialog.dismiss();
                }
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));

                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        };
        timer.start();// 开始计时
    }

    private void startErrorCountDownTime(final long time) {
        if (errorBackTime != null) {
            errorBackTime.cancel();
        }
        errorBackTime = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvErrorBackNow.setText(String.format(getString(R.string.close_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                tvErrorBackNow.setText("关闭");
                tvErrorBackNow.setBackgroundResource(R.drawable.round_corner_back_btn_bg);
                tvErrorBackNow.setClickable(true);
            }
        };
        errorBackTime.start();// 开始计时
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPrintFinishEvent(PrintFinishEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                printFinish(mPrintData.get(0).getPrintId(), orderNo, mPrintData.get(0).getTicketId());
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        if (event != null && event.getData() != null) {
            if (FusionData.mMemData != null) {
                mBinding.tvMemStatus.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
                mBinding.tvMemStatus.setVisibility(View.VISIBLE);
                mBinding.tvPoint.setText(giveIntegral);
                mBinding.tvUpPoint.setText(giveGrowth);
                getCouponList();
                getIntegerAndGrow();
            } else {
                mBinding.tvMemStatus.setText("未登录");
                mBinding.tvPoint.setText("0");
                mBinding.tvUpPoint.setText("0");
                if (AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE).equals("1") || StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE))) {
                    showLoginMemDialog();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                payCode = event.getData().getString(FusionTag.QR_CODE);
                if (timer != null) {
                    timer.cancel();
                }
                if (mustLoginDialog != null && mustLoginDialog.isShowing()) {
                    return;
                }
                if (unMustLoginDialog != null && unMustLoginDialog.isShowing()) {
                    return;
                }
                payOrder(payCode);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void couponRefresh(CouponCheckRefreshEvent event) {
        if (event != null && event.getData() != null) {
            if (StringUtil.isNotEmpty(event.getData().getString(FusionTag.COUPON_ID))) {
                couponPrice = event.getData().getDouble(FusionTag.COUPON_PRICE);
                mBinding.tvCoupon.setText("-￥" + couponPrice);
                mBinding.tvPrice.setText("￥" + DoubleUtils.formatDecimal(packagePrice * sessionNum));
                if (couponPrice > packagePrice * sessionNum) {
                    mBinding.tvOrderPrice.setText("￥" + DoubleUtils.formatDecimal(0));
                } else {
                    mBinding.tvOrderPrice.setText("￥" + DoubleUtils.formatDecimal(totalPrice - couponPrice));
                }
                selectCouponId = event.getData().getString(FusionTag.COUPON_ID);
                getIntegerAndGrow();
            } else {
                couponPrice = 0;
                mBinding.tvPrice.setText("￥" + DoubleUtils.formatDecimal(packagePrice * sessionNum));
                mBinding.tvOrderPrice.setText("￥" + DoubleUtils.formatDecimal(packagePrice * sessionNum));
                mBinding.tvCoupon.setText("未使用优惠券");
                selectCouponId = "";
                mBinding.tvPoint.setText(giveIntegral);
                mBinding.tvUpPoint.setText(giveGrowth);
            }
        }
    }

    private void getIntegerAndGrow() {
        DialogUtil.showLoadingDialog(getContext(), "正在更新套餐信息...");
        JSONObject params = new JSONObject();
        params.put("packageId", packageId);
        params.put("memberUuid", FusionData.mMemData.getUserId());
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("couponRecordId", selectCouponId);
        params.put("buyQuantity", sessionNum);

        HttpHelper.RestClientPostRaw(params, HttpUrl.GET_INTEGRAL_AND_GROW, new ISuccess() {
            @Override
            public void onSuccess(int code, String response) {
                DialogUtil.dismissLoadingDialog();
                try {
                    Type type = new TypeToken<GrowInfoEntity>() {
                    }.getType();
                    Gson gson = new Gson();
                    GrowInfoEntity mData = gson.fromJson(response, type);
                    if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                        mBinding.tvPoint.setText(String.valueOf(mData.getBody().getTotalGiveIntegral()));
                        mBinding.tvUpPoint.setText(String.valueOf(mData.getBody().getTotalGiveGrowth()));
                    }
                } catch (Exception e) {
                }
            }
        }, new IError() {
            @Override
            public void onError(int code, String msg) {
                DialogUtil.dismissLoadingDialog();
            }
        }, new IFailure() {
            @Override
            public void onFailure() {
                DialogUtil.dismissLoadingDialog();
            }
        });
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownBackTime(120);
        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
        FusionCode.QrIsLoading = false;
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (backTimer != null) {
            backTimer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtil.dismissErrorDialog();
        DialogUtil.dismissLoadingDialog();
        cleanSessionInfo();
        EventBus.getDefault().unregister(this);
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        if (timer != null) {
            timer.cancel();
        }
        if (backTimer != null) {
            backTimer.cancel();
        }
        if (couponTipsDialog != null) {
            couponTipsDialog.dismiss();
        }

        if (mustLoginDialog != null) {
            mustLoginDialog.dismiss();
        }
        if (unMustLoginDialog != null) {
            unMustLoginDialog.dismiss();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
